import { NetworkStatus, IRemoteStatus } from './interface';

class Network {
	private static instance: Network | null;

	public amsStatus: NetworkStatus;
	public ccsStatus: NetworkStatus;
	public remoteStatus: IRemoteStatus[];

	static getInstance(): Network {
		// 判断系统是否已经有这个单例
		if (Network.instance === null) {
			Network.instance = new Network();
		}
		return Network.instance; // 单例模式
	}

	constructor() {
		this.amsStatus = ''; // 本地ams网络连接状态['connected','reconnect_failed','reconnecting', 'offline', 'online']
		this.ccsStatus = ''; // 本地ccs网络连接状态['connected','reconnect_failed','reconnecting', 'offline', 'online']
		this.remoteStatus = []; // ccs远端访客和坐席网络连接状态 [{id:id, status:'connected'|'reconnect_failed'|'reconnecting'}]
	}

	public setLocalAmsStatus(status: NetworkStatus) {
		this.amsStatus = status;
	}
	public setLocalCcsStatus(status: NetworkStatus) {
		this.ccsStatus = status;
	}

	public setRemoteStatus(remoteStatus: IRemoteStatus) {
		const { id, status } = remoteStatus;
		const remote = this.findRemoteStatusWithID(id);
		if (remote) {
			const { index } = remote;
			this.remoteStatus[index].status = status;
		}
	}

	public removeRemoteStatus(id: number | string) {
		const remote = this.findRemoteStatusWithID(id);
		if (remote) {
			const { index } = remote;
			this.remoteStatus.splice(index, 1);
		}
	}

	private findRemoteStatusWithID(id: number | string) {
		let resp = null;
		this.remoteStatus.forEach((item, index) => {
			if (item.id === id) {
				resp = { index: index, remoteStatus: item };
			}
		});
		return resp;
	}

	public resetNetworkStatus() {
		return {
			amsStatus: '',
			ccsStatus: '',
			remoteStatus: []
		};
	}
}

export default new Network();
